import React, { useState, useImperativeHandle, useRef, useCallback } from 'react'
import Modal from '@COMPONENTS/Modal/index'
import AtCalendar from '@COMPONENTS/Calendar'
import LoginVerifyBtn from '@COMPONENTS/Button/LoginVerifyBtn'
import i18n from '@I18N'
import { Image, Text, View } from '@tarojs/components'
import Images from '@ASSET/Images'
import Calendar from '@COMPONENTS/Calendar/types/Calendar'
import { showToast } from '@UTILS/common'
import api from '@API'
import { PainLogITF } from '@INTERFACES/PainLog'
import dayjs from 'dayjs'
import Taro from '@tarojs/taro'
import { Analytic_Type } from '@CONSTANTS/analytic'
import style from './MenstruationDialog.module.scss'
interface Props {
  forwardRef: React.MutableRefObject<any>
  onSelectDate: (value: any) => void
  monthPainLogs?: Calendar.Mark[]
  maxDate: string
  pId: string
}
const MenstruationDialog: React.FC<Props> = ({ forwardRef, onSelectDate, monthPainLogs = [], pId, maxDate }) => {
  const [visible, setVisible] = useState(false)
  const [disabled, setDisabled] = useState(true)
  const cacheMark = useRef<{ [key: string]: Calendar.Mark[]}>({})
  const [currentDate, setCurrentDate] = useState<Calendar.SelectedDate>()
  useImperativeHandle(forwardRef, () => ({
    showDialog: (bucket: string) => {
      const current = monthPainLogs.filter(item => item.icon)
      cacheMark.current = { bucket: current }
      setCurrentDate({ arrays: current.map(item => item.value), start: bucket })
      setVisible(true)
      setDisabled(true)
      Taro.hideTabBar()
    }
  }), [monthPainLogs])
  const onMonthChange = useCallback(async value => {
    try {
      const curBucket = dayjs(value).format('YYYY-MM')
      if (cacheMark.current[curBucket]) return
      const result: { PainLogs : PainLogITF[] } = await api.getPatientMonthPainLog({ bucket: curBucket, pId })
      const painLogs = result.PainLogs
      const data: Calendar.Mark[] = []
      painLogs.forEach(item => {
        const { DateBucket, Menstruation } = item
        if (Menstruation) {
          data.push({ value: DateBucket, icon: Menstruation })
        }
      })
      cacheMark.current[curBucket] = data
      const newMoth = data.map(item => item.value)
      setCurrentDate({ arrays: [...(currentDate?.arrays || []), ...newMoth], start: value })
    } catch (e) {
      showToast(e)
    }
  }, [currentDate?.arrays, pId])
  const onCancel = () => {
    Taro.tracker.trackEvent(Analytic_Type.num_cancel_menstruation.eventId)
    setVisible(false)
    Taro.showTabBar()
  }
  const onSave = useCallback(() => {
    Taro.tracker.trackEvent(Analytic_Type.num_save_menstruation.eventId)
    Taro.showTabBar()
    setVisible(false)
    const remoteData: Record<string, string> = {}
    Object.values(cacheMark.current).forEach(item => {
      item.forEach(item2 => {
        const key = item2.value as string
        if (item2.icon) remoteData[key] = key
      })
    })
    const select = currentDate?.arrays?.map(item => ({ DateBucket: item, Status: 'Active' }))
    Object.keys(remoteData).forEach(item => {
      const index = currentDate?.arrays?.indexOf(item) || 0
      if (index < 0) {
        select?.push({ DateBucket: item, Status: 'Archived' })
      }
    })
    onSelectDate(select)
  }, [currentDate?.arrays, onSelectDate])
  const onSelectDateCall = (item: { value: Calendar.SelectedDate }) => {
    setDisabled(false)
    setCurrentDate({ ...currentDate, ...item.value })
  }
  if (!visible) return null
  return (
    <Modal visible onCancel={onCancel} contentClassName={style.radius} showCancel={false}>
      <View className={style.container}>
        <View className={style.title}>
          <Text className={style.text}>请点击选择你的月经期</Text>
          <Image onClick={onCancel} className={style.closeIcon} src={Images.close_common} />
        </View>
        <AtCalendar
          showController
          onMonthChange={onMonthChange}
          className={style.calendar}
          isMultiSelect
          maxDate={maxDate}
          currentDate={currentDate}
          isSkip
          onSelectDate={onSelectDateCall}
        />
        <View className={style.line} />
        <LoginVerifyBtn onClick={onSave} className={`${style.button} ${disabled ? style.disabled : ''}`} disabledVerify disabled={disabled}>
          {i18n.button.save()}
        </LoginVerifyBtn>
      </View>
    </Modal>
  )
}

export default MenstruationDialog
